//
//  UITextField+DFShake.m
//  FrameWork
//
//  Created by 王*风 on ****/5/9.
//

#import "UITextField+DFShake.h"

@implementation UITextField (DFShake)


- (void)df_shake {
    [self df_shake:10 withDelta:5 completion:nil];
}

- (void)df_shake:(int)times withDelta:(CGFloat)delta {
    [self df_shake:times withDelta:delta completion:nil];
}

- (void)df_shake:(int)times withDelta:(CGFloat)delta completion:(void(^)(void))handler {
    [self _df_shake:times direction:1 currentTimes:0 withDelta:delta speed:0.03 shakeDirection:JKShakedDirectionHorizontal completion:handler];
}

- (void)df_shake:(int)times withDelta:(CGFloat)delta speed:(NSTimeInterval)interval {
    [self df_shake:times withDelta:delta speed:interval completion:nil];
}

- (void)df_shake:(int)times withDelta:(CGFloat)delta speed:(NSTimeInterval)interval completion:(void(^)(void))handler {
    [self _df_shake:times direction:1 currentTimes:0 withDelta:delta speed:interval shakeDirection:JKShakedDirectionHorizontal completion:handler];
}

- (void)df_shake:(int)times withDelta:(CGFloat)delta speed:(NSTimeInterval)interval shakeDirection:(JKShakedDirection)shakeDirection {
    [self df_shake:times withDelta:delta speed:interval shakeDirection:shakeDirection completion:nil];
}

- (void)df_shake:(int)times withDelta:(CGFloat)delta speed:(NSTimeInterval)interval shakeDirection:(JKShakedDirection)shakeDirection completion:(void(^)(void))handler {
    [self _df_shake:times direction:1 currentTimes:0 withDelta:delta speed:interval shakeDirection:shakeDirection completion:handler];
}

- (void)_df_shake:(int)times direction:(int)direction currentTimes:(int)current withDelta:(CGFloat)delta speed:(NSTimeInterval)interval shakeDirection:(JKShakedDirection)shakeDirection completion:(void(^)(void))handler {
    [UIView animateWithDuration:interval animations:^{
        self.transform = (shakeDirection == JKShakedDirectionHorizontal) ? CGAffineTransformMakeTranslation(delta * direction, 0) : CGAffineTransformMakeTranslation(0, delta * direction);
    } completion:^(BOOL finished) {
        if(current >= times) {
            [UIView animateWithDuration:interval animations:^{
                self.transform = CGAffineTransformIdentity;
            } completion:^(BOOL finished) {
                if (handler) {
                    handler();
                }
            }];
            return;
        }
        [self _df_shake:(times - 1)
           direction:direction * -1
        currentTimes:current + 1
           withDelta:delta
               speed:interval
      shakeDirection:shakeDirection
          completion:handler];
    }];
}

@end
